package com.link.play.fit.ai.ui.view

import android.content.Context
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.link.play.fit.ai.R

class GradientTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    // 渐变方向
    var orientation: Orientation = Orientation.LEFT_TO_RIGHT
        set(value) {
            field = value
            updateShader()
        }

    // 渐变色数组
    var colors: IntArray = intArrayOf(context.getColor(R.color.color_FDD1AE), context.getColor(R.color.color_FEF3DF))
        set(value) {
            field = value
            updateShader()
        }

    // 渐变位置（可选）
    var positions: FloatArray? = null
        set(value) {
            field = value
            updateShader()
        }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        updateShader()
    }

    private fun updateShader() {
        if (width == 0 || height == 0) return

        val shader = when (orientation) {
            Orientation.LEFT_TO_RIGHT -> LinearGradient(
                0f, 0f, width.toFloat(), 0f,
                colors, positions, Shader.TileMode.CLAMP
            )
            Orientation.TOP_TO_BOTTOM -> LinearGradient(
                0f, 0f, 0f, height.toFloat(),
                colors, positions, Shader.TileMode.CLAMP
            )
            Orientation.DIAGONAL -> LinearGradient(
                0f, 0f, width.toFloat(), height.toFloat(),
                colors, positions, Shader.TileMode.CLAMP
            )
        }

        paint.shader = shader
        invalidate() // 刷新视图
    }

    enum class Orientation {
        LEFT_TO_RIGHT, TOP_TO_BOTTOM, DIAGONAL
    }
}